package com.burger.counter.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.burger.counter.beans.Item;
import com.burger.counter.beans.ShoppingCart;
import com.burger.counter.business.ItemBusiness;

/**
 * Servlet implementation class EditOrderServlet
 */
public class HandleOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    int count=0;   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HandleOrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Item item=null;
		ShoppingCart cart=null;
		
		ArrayList<Item> itemList;
		
		HttpSession session = request.getSession(true);
		cart = (ShoppingCart) session.getAttribute("Cart");
		itemList=cart.getItemInCart();
		
		
		if(request.getParameter("SUBMIT").equals("Remove From Cart"))
		{
		String[] values = request.getParameterValues("ItemId");	
	
		
		for(int i=0;i<values.length;i++)
			System.out.println("VAlue" + values[i]);
		if(itemList != null && values != null)
		{
			for (int j = 0; j < itemList.size(); j++) {
				item=itemList.get(j);
				  if(item.getItemId()==Integer.parseInt(values[0]))
				  {
					  System.out.println("item " + item.getItemName()+ " removed");
					  itemList.remove(j);
				  }
			}
		}
		cart.updateCart(itemList);
		
		session.setAttribute("Cart", cart);
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ViewOrder.jsp");
		dispatcher.forward(request, response);
		}
		
		else if(request.getParameter("SUBMIT").equals("CheckOut"))
		{
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/PickUpTime.jsp");
			dispatcher.forward(request, response);
		}
		else if(request.getParameter("SUBMIT").equals("Cancel Order"))
		{
			itemList.removeAll(itemList);
			System.out.println("Empty List " + itemList.size());
			cart=null;
			
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ViewOrder.jsp");
			dispatcher.forward(request, response);
			
		}
		
	}

}
